<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\admin\validate\Config as ConfigValidate;
use app\common\lib\HttpError;
use Exception;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Log;
use think\Request;

/**
 * @note    配置
 * @author  liujian
 * Class Config
 * @package app\admin\controller
 * @Create  Date : 2021年04月01日 下午1:57:18
 */
class Config extends Base
{
    /**
     * @OA\Get(path="/config/list",
     *   tags={"配置管理"},
     *   summary="配置列表",
     *   @OA\Parameter(name="token", in="header", description="token", @OA\Schema(type="string", default="123456")),
     *     @OA\RequestBody(
     *     @OA\MediaType(
     *       mediaType="multipart/form-data",
     *         @OA\Schema(
     *           @OA\Property(description="map名称和value list原始数组", property="type", type="string", default=""),
     *           @OA\Parameter(name="map 或者list 默认list", in="query", description="backtype", @OA\Schema(type="int", default="1")),
     *           required={"name_value"})
     *       )
     *     ),
     *   @OA\Response(
     *      response=200,
     *      description="The Member",
     *      @OA\JsonContent(type="object",
     *          @OA\Property(property="msg", type="string"),
     *          @OA\Property(property="code", type="integer", default="200"),
     *          @OA\Property(property="data", type="object",
     *               @OA\Property(property="list", type="object",description="列表,具体值参考详情"),
     *          ),
     *      ),
     *   ),
     * )
     */
    public function list()
    {
        //
        $backtype = input("backtype");
        $list = Db::name("config")
            ->select()
            ->toArray();

        if ($backtype && $backtype == "map") {
            foreach ($list as $key => $value) {
                $backlist[$value['name']] = $value['value'];
            }
        } else {
            $backlist = $list;
        }
        return $this->jsonSuccessData("操作成功", $backlist);
    }

    /**
     * @OA\Post(path="/config/save",
     *   tags={"配置管理"},
     *   summary="配置添加/修改",
     *   @OA\Parameter(name="token", in="header", description="token", @OA\Schema(type="string", default="123456")),
     *     @OA\RequestBody(
     *     @OA\MediaType(
     *       mediaType="multipart/form-data",
     *         @OA\Schema(
     *           @OA\Property(description="配置name", property="name", type="string", default=""),
     *           @OA\Property(description="类型 1是json 2是文本", property="type", type="string", default=""),
     *           @OA\Property(description="标题", property="title", type="string", default=""),
     *           @OA\Property(description="内容", property="value", type="string", default=""),
     *           required={"name", "type", "value"})
     *       )
     *     ),
     *   @OA\Response(
     *      response=200,
     *      description="The Member",
     *      @OA\JsonContent(type="object",
     *          @OA\Property(property="msg", type="string"),
     *          @OA\Property(property="code", type="integer", default="200"),
     *          @OA\Property(property="data", type="object",
     *          ),
     *      ),
     *   ),
     * )
     */
    public function save(Request $request, int $id = 0)
    {

        if (!input("name")) throw new ValidateException("参数错误");

        if (input("type") == 1) {

            if (!admin_is_json(input("value"))) throw new ValidateException("非json格式");
            //
            $update_data = array(
                'value'       => input("value"),
                'update_time' => date("Y-m-d H:i:s")
            );
        } else if (input("type") == 2) {

            $update_data = array(
                'title'       => input("title"),
                'value'       => input("value"),
                'update_time' => date("Y-m-d H:i:s")
            );
        }
        $result = Db::name("config")->where('name', input("name"))->update($update_data);
        if (!$result) throw new Exception("操作失败");
        addAdminLog("修改某个配置信息:" . json_encode($update_data), '修改某个配置信息');
        return $this->jsonSuccessData("操作成功");

    }

    /**
     * @OA\Post(path="/config/save_all",
     *   tags={"配置管理"},
     *   summary="配置全部修改",
     *   @OA\Parameter(name="token", in="header", description="token", @OA\Schema(type="string", default="123456")),
     *     @OA\RequestBody(
     *     @OA\MediaType(
     *       mediaType="multipart/form-data",
     *         @OA\Schema(
     *           @OA\Property(description="二维数组 列：[{name=>1123,value=>json}]", property="name_value", type="string", default=""),
     *           required={"name_value"})
     *       )
     *     ),
     *   @OA\Response(
     *      response=200,
     *      description="The Member",
     *      @OA\JsonContent(type="object",
     *          @OA\Property(property="msg", type="string"),
     *          @OA\Property(property="code", type="integer", default="200"),
     *          @OA\Property(property="data", type="object",
     *          ),
     *      ),
     *   ),
     * )
     */
    public function save_all()
    {
        try {
            $name_value = input("value");
            // 启动事务
            Db::startTrans();

            validate(ConfigValidate::class)->check($name_value);

            foreach ($name_value as $key => $val) {
                if (empty($key)) throw new Exception("参数错误");
                $update_data = array(
                    'value'       => $val,
                    'update_time' => date("Y-m-d H:i:s")
                );
                Db::name("config")->where('name', $key)->update($update_data);
            }
            // 提交事务
            addAdminLog("批量修改配置信息:" . json_encode($name_value), '批量修改配置信息');
            Db::commit();
            return $this->jsonSuccessData("操作成功");
        } catch (ValidateException $e) {
            Log::record('【配置】' . $e->getMessage() . $e->getFile() . $e->getLine());
            return $this->jsonFailData($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            Log::record('【配置】' . $e->getMessage() . $e->getFile() . $e->getLine());
            return $this->jsonFailData(HttpError::SERVER_INTERNAL_ERROR[1]);
        }
    }


    /**
     * @OA\Get(path="/config/read",
     *   tags={"配置管理"},
     *   summary="配置详情",
     *   @OA\Parameter(name="token", in="header", description="token", @OA\Schema(type="string", default="123456")),
     *   @OA\Parameter(name="name", in="query", description="配置name", @OA\Schema(type="int", default="site_config")),
     *   @OA\Response(
     *       response=200,
     *       description="The Member",
     *       @OA\JsonContent(type="object",
     *           @OA\Property(property="msg", type="string"),
     *           @OA\Property(property="code", type="integer", default="200"),
     *           @OA\Property(property="data", type="object",
     *                @OA\Property(property="info", type="object",description="详情"),
     *           ),
     *       ),
     *    ),
     * )
     */
    public function read($name)
    {
        //
        $info = Db::name("config")->where('name', $name)->find();
        if (empty($info)) {
            return $this->jsonFailData('查询失败，未找到该配置');
        }
        return $this->jsonSuccessData("操作成功", [
            'info' => $info
        ]);
    }

}
